﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DrawRectangle
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            DoubleBuffered = true;
            BackColor = Color.GreenYellow;
        }

        Point myDown = Point.Empty;
        Point mCur = Point.Empty;

        private void Form1_MouseDown(object sender, MouseEventArgs e)
        {
            myDown = e.Location;//按下记录鼠标坐标
        }

        private void Form1_MouseUp(object sender, MouseEventArgs e)
        {
            myDown = Point.Empty;//抬起清空值
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            //鼠标左键按下 记录可以移动的光标坐标 并刷新
            if (e.Button != MouseButtons.Left)
                return;
            mCur = e.Location;
            Invalidate();
        }

        private void Form1_Paint(object sender, PaintEventArgs e)
        {
            //绘图
            if (myDown == Point.Empty)
                return;
            Size s = new Size(Math.Abs(myDown.X - mCur.X), 
                Math.Abs(myDown.Y - mCur.Y));
            Point topLeft = new Point(Math.Min(myDown.X, mCur.X), 
                Math.Min(myDown.Y, mCur.Y));//左上角的点
            Rectangle rect = new Rectangle(topLeft, s);
            e.Graphics.Clear(this.BackColor);
            e.Graphics.FillRectangle(Brushes.Bisque, rect);//矩形画出后的填充色
            e.Graphics.DrawRectangle(Pens.Red, rect);


        }
    }
}
